package com.currentcms.client.dialog;

import com.currentcms.client.event.CancelEvent;
import com.currentcms.client.event.CancelHandler;
import com.currentcms.client.event.ConfirmEvent;
import com.currentcms.client.event.ConfirmHandler;
import com.currentcms.client.event.HasCancelHandlers;
import com.currentcms.client.event.HasConfirmHandlers;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class ConfirmDialog extends DialogBox implements HasConfirmHandlers, HasCancelHandlers
{
	public static ConfirmDialog get(String msg, ConfirmHandler confirm, CancelHandler cancel)
	{
		ConfirmDialog d = new ConfirmDialog();
		d.setMessage(msg);
		d.addConfirmHandler(confirm);
		d.addCancelHandler(cancel);
		return d;
	}
	
	private final HandlerManager _handler_manager = new HandlerManager(this);
	private Label l;
	
	public ConfirmDialog()
	{
		setGlassEnabled(true);
		setModal(true);
		setSize("200px", "100px");
		super.setWidget(create_ui());
	}

	private Widget create_ui()
	{
		FlowPanel p = new FlowPanel();

		l = new Label();
		l.setText("Really??");

		Button y = new Button("OK");
		y.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				hide();
				_handler_manager.fireEvent(new ConfirmEvent(ConfirmDialog.this));
			}
		});
		Button n = new Button("Cancel");
		n.addClickHandler(new ClickHandler()
		{
			@Override
			public void onClick(ClickEvent event)
			{
				hide();
				_handler_manager.fireEvent(new CancelEvent(ConfirmDialog.this));
			}
		});
		p.add(l);
		p.add(y);
		p.add(n);

		return p;
	}
	
	public void setMessage(String s)
	{
		l.setText(s);
	}
	
	public void setRelativePosition(Widget sender)
	{
		int left = sender.getAbsoluteLeft();
        int top = sender.getAbsoluteTop() ;
//        if (top>Window.getClientHeight()+Window.getScrollTop())
//        	top = Window.getClientHeight()+Window.getScrollTop();
        setPopupPosition(left, top);
	}

	@Override
	public HandlerRegistration addConfirmHandler(ConfirmHandler handler)
	{
		return _handler_manager.addHandler(ConfirmEvent.getType(), handler);
	}

	@Override
	public HandlerRegistration addCancelHandler(CancelHandler handler)
	{
		return _handler_manager.addHandler(CancelEvent.getType(), handler);
	}

}
